<template>
    <div class="view_banner">
        <card>
            <template #actions>
                <el-button type="primary" class="add_button" @click="add">添加横幅</el-button>
            </template>
            <template #default>
                <template>
                    <el-tabs v-model="tabName">
                        <el-tab-pane v-for="item in tableData" :key="item.groupId" :label="item.groupName" :name="item.groupId">
                            <el-table :data="item.childs">
                                <el-table-column label="#" type="index" align="center"></el-table-column>
                                <el-table-column label="路径" prop="redirect"></el-table-column>
                                <el-table-column label="描述" prop="description"></el-table-column>
                                <el-table-column label="类型">
                                    <template #default="{ row: { linkType } }">
                                        <el-tag :type="bannerTypes[linkType].tagType">
                                            {{ bannerTypes[linkType].text }}
                                        </el-tag>
                                    </template>
                                </el-table-column>
                                <el-table-column label="预览">
                                    <template #default="{ row }">
                                        <img :src="row.pic" />
                                    </template>
                                </el-table-column>
                                <el-table-column label="排序" prop="picSort"></el-table-column>
                                <el-table-column label="操作">
                                    <template v-slot="{ row }">
                                        <el-button type="text" @click="edit(row)">编辑</el-button>
                                        <el-button type="text" @click="_delete(row.bannerId)">删除</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-tab-pane>
                    </el-tabs>
                </template>
                <!-- <template v-else>
                    <div style="padding: 240px; text-align: center">图像转码中...</div>
                </template> -->
            </template>
        </card>

        <!-- 图片上传对话框 -->
        <el-dialog :title="dialogTitle" :visible.sync="visible" @closed="onClosed">
            <el-form label-position="top">
                <el-row :gutter="12">
                    <el-col :span="8">
                        <el-form-item label="定位">
                            <el-select v-model="formData.locationCode" :disabled="editing">
                                <el-option
                                    v-for="(val, key) in bannerPositions"
                                    :key="key"
                                    :value="+key"
                                    :label="val.text"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="类型">
                            <el-select v-model="formData.linkType">
                                <el-option
                                    v-for="(val, key) in bannerTypes"
                                    :key="key"
                                    :value="+key"
                                    :label="val.text"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="排序">
                            <el-input v-model="formData.picSort" type="number" min="0" max="99" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="跳转地址">
                    <el-input v-model="formData.redirect" />
                </el-form-item>
                <el-form-item label="描述">
                    <el-input v-model="formData.description" />
                </el-form-item>
                <el-form-item label="图片上传">
                    <el-upload
                        drag
                        :action="uploaderData.action"
                        :data="uploaderData.data"
                        :auto-upload="false"
                        :show-file-list="false"
                        :on-change="handleFileChange"
                        :on-success="handleFileUploadSuccess"
                        ref="uploader"
                    >
                        <template v-if="objectUrl">
                            <img class="preview_image" :src="objectUrl" />
                        </template>
                        <template v-else>
                            <i class="el-icon-upload"></i>
                            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                        </template>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template v-slot:footer>
                <el-button type="primary" @click="save" :disabled="isButtonDisabled">保存</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import { getDeletionOptions, getQueryOptions } from '../../mixins';
import { v4 as getUUIDV4 } from 'uuid';
// import { toJpeg } from '../../functions';

const defaultFormData = {
    pic: '',
    redirect: '',
    picSort: 99,
    description: '',
    locationCode: 1,
    linkType: 1,
};

const _defaultFormData = Object.assign({}, defaultFormData);

export default {
    data() {
        return {
            visible: false,
            tableData: [],
            // 是否在编辑
            editing: false,

            tabName: '1',

            formData: defaultFormData,

            uploaderData: {
                action: '',
                data: null,
            },

            fileInfo: null,

            // 文件blob链接
            objectUrl: '',
        };
    },

    mixins: [
        getQueryOptions({
            apiurl: '/yxl/platform/findBanner',
            params: {
                categoryId: 'catalogId',
            },
            // fnAfterQuery(res) {
            //     let allBannerUrls = res.reduce((accumulator, currentValue) => {
            //         return accumulator.concat(currentValue.childs ? currentValue.childs.map(banner => banner.pic) : []);
            //     }, []);

            //     toJpeg(allBannerUrls).then($res => {
            //         // i记录$res索引
            //         // j记录组的索引
            //         // k记录组内横幅索引
            //         for (let i = 0, j = 0, k = 0; i < $res.length; i++, k++) {
            //             if (!res[j].childs) {
            //                 j++;
            //                 k = 0;
            //             }

            //             if (k < res[j].childs.length) {
            //                 res[j].childs[k].native_url = $res[i];
            //             } else {
            //                 j++;
            //                 k = -1;
            //                 i--;
            //             }
            //         }

            //         this.tableData = res;
            //     });

            //     return;
            // },
        }),

        getDeletionOptions({
            apiurl: '/yxl/platform/deleteBanner',
            params: 'bannerId',
        }),
    ],

    computed: {
        // 对话框标题
        dialogTitle() {
            return this.editing ? '编辑横幅' : '添加横幅';
        },

        categoryId() {
            return this.$route.query.categoryId;
        },

        // 文件扩展名
        fileExpansion() {
            let name = this.fileInfo ? this.fileInfo.name : '';
            if (name) {
                return name.substr(name.lastIndexOf('.'));
            }
        },

        // 按钮是否禁用
        isButtonDisabled() {
            if (this.editing) {
                return !this.formData.redirect || !this.formData.description;
            }

            return !this.formData.redirect || !this.formData.description || !this.fileInfo;
        },

        // >>>>> 横幅状态常量
        // 横幅类型
        bannerTypes() {
            return {
                1: { text: '网址' },
                2: { tagType: 'success', text: '产品' },
                3: { tagType: 'warning', text: '分类' },
                4: { tagType: 'danger', text: '关键字' },
            };
        },

        // 横幅定位
        bannerPositions() {
            return {
                1: { text: '轮播', suffix: '/banner' },
                2: { text: '单张', suffix: '/banner' },
                3: { text: '导航列表', suffix: '/catalogLogo' },
            };
        },
        // 横幅状态常量 <<<<<
    },

    watch: {
        categoryId() {
            this.tableData = [];
            this.query();
        },

        tabName(v){
            this.formData.locationCode = +v;
        }
    },

    methods: {
        // 添加
        add() {
            this.editing = false;
            this.visible = true;
        },

        // 编辑
        edit(row) {
            this.editing = true;
            // 表单赋值
            this.formData.bannerId = row.bannerId;
            this.formData.description = row.description;
            this.formData.picSort = row.picSort;
            this.formData.pic = row.pic;
            this.formData.redirect = row.redirect;
            this.formData.linkType = row.linkType;
            // 对象url
            this.objectUrl = row.pic;

            this.visible = true;
        },

        onClosed() {
            delete this.formData.bannerId;
            Object.assign(this.formData, _defaultFormData);
            // 清除文件实例
            this.fileInfo = null;
            this.objectUrl = '';
        },

        // 处理文件变化
        handleFileChange(file, fileList) {
            // 文件列表数量大于一时删除第一个，限制上传文件数量是一
            if (fileList.length > 1) {
                fileList.shift();
            }

            // 保存当前文件对象于实例
            this.fileInfo = file.raw;

            // 如果原先存有链接则销毁原先的链接
            if (this.objectUrl) {
                URL.revokeObjectURL(this.objectUrl);
            }

            // 创建blob链接预览图片
            this.objectUrl = URL.createObjectURL(file.raw);
        },

        // 处理文件上传成功
        handleFileUploadSuccess() {
            // this.formData.pic = this.fullUrl;
            let data = Object.assign({ catalogId: this.categoryId }, this.formData);
            // 如果在编辑则删除轮播定位参数
            if (this.editing) {
                // delete data.locationCode;
                // delete this.formData.locationCode;
            }

            this.$put(`/yxl/platform/${this.editing ? 'update' : 'save'}Banner`, data).then(res => {
                this.visible = false;
                this.query();
            });
        },

        save() {
            if (this.fileInfo) {
                let uuid = getUUIDV4();
                let fileName = this.fileInfo.name;
                let fileExpansion = fileName.substr(fileName.lastIndexOf('.'));
                let suffix = this.bannerPositions[this.formData.locationCode].suffix;

                this.$get('/yxl/oss/policy').then(res => {
                    let path = `${res.dir}/${uuid}${fileExpansion}`;

                    this.formData.pic = `${res.host}/${path}${suffix}`;

                    this.uploaderData.action = res.host;

                    this.uploaderData.data = {
                        key: path,
                        policy: res.policy,
                        signature: res.signature,
                        OSSAccessKeyId: res.accessid,
                        success_action_status: '200',
                    };

                    this.$nextTick(this.$refs.uploader.submit);
                });
            } else {
                this.handleFileUploadSuccess();
            }
        },
    },
};
</script>